package tsm.network;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.util.Vector;

import tsm.constant.ClientConstant;
import tsm.constant.Language;
import tsm.main.Core;
import tsm.main.MagicExecutor;
import tsm.model.Buddy;
import tsm.widget.MagicPage;
import tsm.widget.Page;

import com.core.tsm.Button;
import com.core.tsm.Command;
import com.core.tsm.Component;
import com.core.tsm.Container;
import com.core.tsm.Display;
import com.core.tsm.Image;
import com.core.tsm.Label;
import com.core.tsm.layouts.BorderLayout;
import com.core.tsm.list.DefaultListModel;

public class BeUMessageHandler {
	public static BeUMessageHandler instance = new BeUMessageHandler();

	public void onDisconnected() {
		//		System.out.println("[NOTIFY] onDisconnected");
		Page p = null;
		if (Core.getInstance().isLoginSuccess) {
			p = Core.getInstance().clearAllPage();
			Core.getInstance().logOff();
		}
		if (Core.getInstance().isBegin) {
			new Thread(new Runnable() {
				public void run() {
					Core.getInstance().showInfoDialog(Language.WARN[ClientConstant.LANGUAGE], Language.DISCONNECT[ClientConstant.LANGUAGE]);
				}
			}).start();
		} else {
			Core.getInstance().onPopupMessageComing(Language.DISCONNECT[ClientConstant.LANGUAGE], p);
		}
	}

	public void onConnectionFail() {
		//		System.out.println("[NOTIFY] onConnectionFail");
		try {
			DataInputStream in = Core.getResourceOverHTTP("http://banngoisao.com/sys/secret.txt", "text/plain");
			ByteArrayOutputStream bytestream = new ByteArrayOutputStream();
			int ch;
			while ((ch = in.read()) != -1) {
				bytestream.write(ch);
			}
			String str = new String(bytestream.toByteArray());
			bytestream.close();
			//			System.out.println("str2 " + str);
			String[] ips = new String[1];
			ips[0] = str.substring(0, str.indexOf(":"));
			int[] ports = new int[1];
			ports[0] = Integer.parseInt(str.substring(str.indexOf(":") + 1));
			Core.getInstance().onIpListComing(ips, ports);
		} catch (Exception e) {
			e.printStackTrace();
		}

		Command tryCommand = new Command(Language.TRY_AGAIN[ClientConstant.LANGUAGE], ClientConstant.TRY_AGAIN_CMD);
		if (Core.getInstance().splashPage != null) {
			Core.getInstance().splashPage.addCommand(tryCommand, 0);
			Command closeCommand = new Command(Language.EXIT[ClientConstant.LANGUAGE], ClientConstant.EXIT_CMD);
			Core.getInstance().splashPage.addCommand(closeCommand, 1);
		}
		Page p = null;
		if (Core.getInstance().isLoginSuccess) {
			p = Core.getInstance().clearAllPage();
			Core.getInstance().logOff();
		}
		if (Core.getInstance().isBegin) {
			new Thread(new Runnable() {
				public void run() {
					Core.getInstance().showInfoDialog(Language.WARN[ClientConstant.LANGUAGE], Language.CONNECTION_PROBLEM[ClientConstant.LANGUAGE]);
				}
			}).start();
		} else {
			Core.getInstance().onPopupMessageComing(Language.CONNECTION_PROBLEM[ClientConstant.LANGUAGE], p);
		}
	}

	public void onConnectOK() {
		//		System.out.println("[NOTIFY] onConnectOK");
		String platform = System.getProperty("microedition.platform");
		//		System.out.println("==============platform " + platform);
		if (Core.getInstance().isBegin) {
			BeUSession.requestIpList(ClientConstant.VIETNAMESE_LANGUAGE);
		}
		BeUSession.clientInfo(ClientConstant.PARTNER_ID, platform == null ? "null" : platform, ClientConstant.APP_ID, ClientConstant.VERSION, Display.getInstance()
				.getDisplayWidth(), Display.getInstance().getDisplayHeight());
	}

	public void processMessage(byte[] data) {
		try {
			Message msg = Message.createMessageToRead(data);
			ByteArrayInputStream buffer = msg.getInputStream();
			try {
				//			System.out.println("processMessage data.length " + data.length);
				int type = msg.getType();
				//		System.out.println("[VitalkMessageHandler] type = " + type);
				switch (type) {
				case ClientConstant.RESPONSE_IP_LIST_BEAN: {
					int n = SerializeHelper.readInt(buffer);
					String[] ips = new String[n];
					for (int i = 0; i < n; i++) {
						ips[i] = SerializeHelper.readString(buffer);
					}
					int m = SerializeHelper.readInt(buffer);
					int[] ports = new int[m];
					for (int i = 0; i < m; i++) {
						ports[i] = SerializeHelper.readInt(buffer);
					}
					Core.getInstance().onIpListComing(ips, ports);
					break;
				}
				case ClientConstant.MAGIC_PAGE_DOWNLOAD_BEAN: {
					byte[] executeCode = SerializeHelper.readBytes(buffer);
					ByteArrayInputStream b = new ByteArrayInputStream(executeCode);
					MagicExecutor.deCompilePage(b, true);
					break;
				}
				case ClientConstant.MAGIC_PAGE_CHECKSUM_BEAN: {
					int pageId = SerializeHelper.readInt(buffer);
					int checkSum = SerializeHelper.readInt(buffer);
					Core.getInstance().onMagicPageCheckSumComing(pageId, checkSum);
					break;
				}
				case ClientConstant.MAGIC_PAGE_CHECKSUM_DOWNLOAD_BEAN: {
					int pageId = SerializeHelper.readInt(buffer);
					int checkSum = SerializeHelper.readInt(buffer);
					byte[] executeCode = SerializeHelper.readBytes(buffer);
					Core.getInstance().saveMagicDataToRMS(pageId, checkSum, executeCode);
					ByteArrayInputStream b = new ByteArrayInputStream(executeCode);
					MagicExecutor.deCompilePage(b, true);
					break;
				}
				case ClientConstant.LOGIN_RESULT_BEAN: {
					// login success
					String username = SerializeHelper.readString(buffer);
					Core.getInstance().username = username;
					Core.getInstance().isLoginSuccess = true;
					int checkSum = Core.getInstance().loadCheckSumFromRMS(username);
					//			System.out.println("CheckSum RMS = " + checkSum);
					if (checkSum != -1) {
						Core.getInstance().loadBuddyFromRMS(username);
					}
					BeUSession.requestFriendList(checkSum);
					BeUSession.requestBlackList();
					break;
				}
				case ClientConstant.FRIENDLIST_BEAN: {
					int checkSum = SerializeHelper.readInt(buffer);
					int n = SerializeHelper.readInt(buffer);
					//			System.out.println("FRIENDLIST_BEAN n = " + n + " checkSum = " + checkSum);
					DefaultListModel buddies = new DefaultListModel();
					if (n > 0) {
						for (int i = 0; i < n; i++) {
							if (SerializeHelper.readByte(buffer) != -1) {
								long userId = SerializeHelper.readLong(buffer);
								String userName = SerializeHelper.readString(buffer);
								byte status = SerializeHelper.readByte(buffer);
								byte level = SerializeHelper.readByte(buffer);
								//						System.out.println("FriendList: " + userName + " " + status);
								Buddy buddy = new Buddy();
								buddy.setUserId(userId);
								buddy.setAvatarId(-1);
								buddy.setUsername(userName);
								buddy.setLevel(level);

								Label description = new Label(Core.getInstance().swImage);
								description.setTextPosition(Label.LEFT);
								description.getSelectedStyle().setBgTransparency(255);
								description.getSelectedStyle().setBgColor(0x138ef6);
								description.getSelectedStyle().setPadding(Button.TOP, 0);
								description.getSelectedStyle().setMargin(Button.TOP, 0);
								description.getSelectedStyle().setPadding(Button.BOTTOM, 1);
								description.getSelectedStyle().setMargin(Button.BOTTOM, 1);
								description.getSelectedStyle().setPadding(Button.LEFT, 0);
								description.getSelectedStyle().setMargin(Button.LEFT, 0);
								description.getSelectedStyle().setPadding(Button.RIGHT, 0);
								description.getSelectedStyle().setMargin(Button.RIGHT, 0);
								description.setFocus(true);
								Label titleLabel = new Label("");
								titleLabel.getSelectedStyle().setBgTransparency(255);
								titleLabel.getSelectedStyle().setBgColor(0x138ef6);
								titleLabel.getSelectedStyle().setPadding(Button.TOP, 0);
								titleLabel.getSelectedStyle().setMargin(Button.TOP, 0);
								titleLabel.getSelectedStyle().setPadding(Button.BOTTOM, 1);
								titleLabel.getSelectedStyle().setMargin(Button.BOTTOM, 1);
								titleLabel.getSelectedStyle().setPadding(Button.LEFT, 0);
								titleLabel.getSelectedStyle().setMargin(Button.LEFT, 0);
								titleLabel.getSelectedStyle().setPadding(Button.RIGHT, 0);
								titleLabel.getSelectedStyle().setMargin(Button.RIGHT, 0);
								Container selected = new Container(new BorderLayout());
								selected.getSelectedStyle().setPadding(Button.TOP, 0);
								selected.getSelectedStyle().setMargin(Button.TOP, 0);
								selected.getSelectedStyle().setPadding(Button.BOTTOM, 0);
								selected.getSelectedStyle().setMargin(Button.BOTTOM, 0);
								selected.getSelectedStyle().setPadding(Button.LEFT, 0);
								selected.getSelectedStyle().setMargin(Button.LEFT, 0);
								selected.getSelectedStyle().setPadding(Button.RIGHT, 0);
								selected.getSelectedStyle().setMargin(Button.RIGHT, 0);
								selected.addComponent(BorderLayout.CENTER, titleLabel);
								selected.addComponent(BorderLayout.EAST, description);
								titleLabel.setFocus(true);
								description.setFocus(true);
								buddy.setAvatarLabel(description);
								buddy.setStatusLabel(titleLabel);
								buddy.setAvatarContainer(selected);

								buddy.setStatus(status);
								buddies.addItem(buddy);
							}
						}
					}
					Core.getInstance().onFriendListComing(checkSum, buddies);
					break;
				}
				case ClientConstant.FRIEND_LIST_STATUS_BEAN: {
					int n = SerializeHelper.readInt(buffer);
					long[] userIds = new long[n];
					if (n > 0) {
						for (int i = 0; i < n; i++) {
							long userId = SerializeHelper.readLong(buffer);
							userIds[i] = userId;
						}
					}
					byte[] levelData = SerializeHelper.readBytes(buffer);
					Core.getInstance().updateStatusOnline(userIds, levelData);
					break;
				}
				case ClientConstant.ADD_FRIEND_RESPONSE_BEAN: {
					String name = SerializeHelper.readString(buffer);
					boolean accepted = SerializeHelper.readBoolean(buffer);
					if (accepted) {
						Core.getInstance().onPopupMessageComing(name + Language.AGREE_ADD[ClientConstant.LANGUAGE], null);
					} else {
						Core.getInstance().onPopupMessageComing(name + Language.DISAGREE_ADD[ClientConstant.LANGUAGE], null);
					}
					break;
				}
				case ClientConstant.BUDDY_INFO_BEAN: {
					long userId = SerializeHelper.readLong(buffer);
					String userName = SerializeHelper.readString(buffer);
					byte status = SerializeHelper.readByte(buffer);
					byte level = SerializeHelper.readByte(buffer);
					Buddy buddy = new Buddy();
					buddy.setUserId(userId);
					buddy.setUsername(userName);
					buddy.setStatus(status);
					buddy.setLevel(level);
					Label description = new Label(Core.getInstance().swImage);
					description.setTextPosition(Label.LEFT);
					description.getSelectedStyle().setBgTransparency(255);
					description.getSelectedStyle().setBgColor(0x138ef6);
					description.getSelectedStyle().setPadding(Button.TOP, 0);
					description.getSelectedStyle().setMargin(Button.TOP, 0);
					description.getSelectedStyle().setPadding(Button.BOTTOM, 1);
					description.getSelectedStyle().setMargin(Button.BOTTOM, 1);
					description.getSelectedStyle().setPadding(Button.LEFT, 0);
					description.getSelectedStyle().setMargin(Button.LEFT, 0);
					description.getSelectedStyle().setPadding(Button.RIGHT, 0);
					description.getSelectedStyle().setMargin(Button.RIGHT, 0);
					description.setFocus(true);
					Label titleLabel = new Label("");
					titleLabel.getSelectedStyle().setBgTransparency(255);
					titleLabel.getSelectedStyle().setBgColor(0x138ef6);
					titleLabel.getSelectedStyle().setPadding(Button.TOP, 0);
					titleLabel.getSelectedStyle().setMargin(Button.TOP, 0);
					titleLabel.getSelectedStyle().setPadding(Button.BOTTOM, 1);
					titleLabel.getSelectedStyle().setMargin(Button.BOTTOM, 1);
					titleLabel.getSelectedStyle().setPadding(Button.LEFT, 0);
					titleLabel.getSelectedStyle().setMargin(Button.LEFT, 0);
					titleLabel.getSelectedStyle().setPadding(Button.RIGHT, 0);
					titleLabel.getSelectedStyle().setMargin(Button.RIGHT, 0);
					Container selected = new Container(new BorderLayout());
					selected.getSelectedStyle().setPadding(Button.TOP, 0);
					selected.getSelectedStyle().setMargin(Button.TOP, 0);
					selected.getSelectedStyle().setPadding(Button.BOTTOM, 0);
					selected.getSelectedStyle().setMargin(Button.BOTTOM, 0);
					selected.getSelectedStyle().setPadding(Button.LEFT, 0);
					selected.getSelectedStyle().setMargin(Button.LEFT, 0);
					selected.getSelectedStyle().setPadding(Button.RIGHT, 0);
					selected.getSelectedStyle().setMargin(Button.RIGHT, 0);
					selected.addComponent(BorderLayout.CENTER, titleLabel);
					selected.addComponent(BorderLayout.EAST, description);
					titleLabel.setFocus(true);
					description.setFocus(true);
					buddy.setAvatarLabel(description);
					buddy.setStatusLabel(titleLabel);
					buddy.setAvatarContainer(selected);

					//			System.out.println("BUDDY_INFO_BEAN comming " + userName);
					Core.getInstance().onBuddyInfoComing(buddy);
					break;
				}
				case ClientConstant.RESPONSE_LAZY_BUDDY_INFO_BEAN: {
					long userId = SerializeHelper.readLong(buffer);
					int avatarId = SerializeHelper.readInt(buffer);
					Core.getInstance().onLazyBuddyInfoComing(userId, avatarId);
					break;
				}
				case ClientConstant.CHANGE_AVATAR_BEAN: {
					long userId = SerializeHelper.readLong(buffer);
					int avatarId = SerializeHelper.readInt(buffer);
					//			System.out.println("CHANGE_AVATAR_BEAN comming " + userId);
					Core.getInstance().onChangeAvatarBeanComing(userId, avatarId);
					break;
				}
				case ClientConstant.IMAGE_AVATAR_RESULT_BEAN: {
					//			System.out.println("IMAGE_AVATAR_RESULT_BEAN comming");
					int avatarId = SerializeHelper.readInt(buffer);
					long userId = SerializeHelper.readLong(buffer);
					byte[] imageData = SerializeHelper.readBytes(buffer);
					//			System.out.println("IMAGE_AVATAR_RESULT_BEAN comming " + avatarId);
					Core.getInstance().onImageAvatarResultComing(avatarId, userId, imageData);
					break;
				}
				case ClientConstant.BLACK_LIST_BEAN: {
					int n = SerializeHelper.readInt(buffer);
					DefaultListModel bl = new DefaultListModel();
					if (n > 0) {
						for (int i = 0; i < n; i++) {
							String userName = SerializeHelper.readString(buffer);
							bl.addItem(userName);
						}
					}
					Core.getInstance().onBlackListComing(bl);
					break;
				}
				case ClientConstant.POPUP_MESSAGE_BEAN: {
					//			System.out.println("PopMessageComing..................");
					String content = SerializeHelper.readString(buffer);
					Core.getInstance().onPopupMessageComing(content, null);
					break;
				}
				case ClientConstant.CHAT_BEAN: {
					long userId = SerializeHelper.readLong(buffer);
					String msgChat = SerializeHelper.readString(buffer);
					Core.getInstance().onChatMessageComing(userId, msgChat);
					break;
				}
				case ClientConstant.BUZZ_BEAN: {
					String from = SerializeHelper.readString(buffer);
					Core.getInstance().onBuzzComing(from);
					break;
				}
				case ClientConstant.HANDSHAKE_CHAT_BEAN: {
					String from = SerializeHelper.readString(buffer);
					String msgChat = SerializeHelper.readString(buffer);
					Core.getInstance().onHandshakeChatMessageComing(from, msgChat);
					break;
				}
				case ClientConstant.RESPONSE_USERID_BEAN: {
					String name = SerializeHelper.readString(buffer);
					long id = SerializeHelper.readLong(buffer);
					Core.getInstance().onUserIdComing(name, id);
					break;
				}
				case ClientConstant.NOTIFY_CHANGE_STATUS_BEAN: {
					String username = SerializeHelper.readString(buffer);
					byte status = SerializeHelper.readByte(buffer);
					//			String blast = SerializeHelper.readString(buffer);
					Core.getInstance().onChangeStatusComing(username, status);
					break;
				}
				case ClientConstant.CONFERENCE_INFO_BEAN: {
					long conferenceId = SerializeHelper.readLong(buffer);
					boolean isStart = SerializeHelper.readBoolean(buffer);
					String title = SerializeHelper.readString(buffer);
					int n = SerializeHelper.readInt(buffer);
					Vector ul = new Vector();
					if (n > 0) {
						for (int i = 0; i < n; i++) {
							String username = SerializeHelper.readString(buffer);
							ul.addElement(username);
						}
					}
					Core.getInstance().createConferencePage(conferenceId, title, true, isStart, ul);
					break;
				}
				case ClientConstant.CONFERENCE_INVITE_RESULT_BEAN: {
					long conferenceId = SerializeHelper.readLong(buffer);
					String username = SerializeHelper.readString(buffer);
					boolean result = SerializeHelper.readBoolean(buffer);
					//			System.out.println("CONFERENCE_INVITE_RESULT_BEAN " + username + " " + result + " " + conferenceId);
					Core.getInstance().joinConference(conferenceId, username, result);
					break;
				}
				case ClientConstant.CONFERENCE_LEAVE_BEAN: {
					long conferenceId = SerializeHelper.readLong(buffer);
					String username = SerializeHelper.readString(buffer);
					Core.getInstance().leaveConference(conferenceId, username);
					break;
				}
				case ClientConstant.CONFERENCE_NOTIFY_BE_KICK_BEAN: {
					long conferenceId = SerializeHelper.readLong(buffer);
					String roomName = SerializeHelper.readString(buffer);
					Core.getInstance().onBeKickConference(conferenceId, roomName);
					break;
				}
				case ClientConstant.CONFERENCE_CHAT_BEAN: {
					long conferenceId = SerializeHelper.readLong(buffer);
					String username = SerializeHelper.readString(buffer);
					String content = SerializeHelper.readString(buffer);
					Core.getInstance().chatConference(conferenceId, username, content);
					break;
				}
				case ClientConstant.CONFERENCE_ASK_JOIN_BEAN: {
					long conferenceId = SerializeHelper.readLong(buffer);
					String inviter = SerializeHelper.readString(buffer);
					String roomName = SerializeHelper.readString(buffer);
					Core.getInstance().onAskJoinConferenceComing(conferenceId, inviter, roomName);
					break;
				}
				case ClientConstant.RESPONSE_IMAGE_PAGE_BEAN: {
					//			System.out.println(">>>>>>>>>>>>>RESPONSE_IMAGE_PAGE_BEAN");
					int pageId = SerializeHelper.readInt(buffer);
					int componentId = SerializeHelper.readInt(buffer);
					int imageId = SerializeHelper.readInt(buffer);
					byte[] imageData = SerializeHelper.readBytes(buffer);
					Page page = Core.getInstance().getPageById(pageId);
					if (page != null && page instanceof MagicPage) {
						Component com = ((MagicPage) page).getComponentById(componentId);
						if (com != null && com instanceof Label) {
							((Label) com).setIcon(Image.createImage(imageData, 0, imageData.length));
						}
					}
					break;
				}
				case ClientConstant.REQUEST_UPLOAD_RESULT_BEAN: {
					long sessionId = SerializeHelper.readLong(buffer);
					BeUSession.sessionId = sessionId;
					BeUSession.uploadChunk(0);
					break;
				}
				case ClientConstant.CHUNK_ACK_BEAN: {
					long sessionId = SerializeHelper.readLong(buffer);
					int chunkAck = SerializeHelper.readInt(buffer);
					if (sessionId == BeUSession.sessionId) {
						BeUSession.uploadChunk(chunkAck + 1);
					} else {
						//				System.out.println("Not sync sessionId");
					}
					break;
				}
				// case ClientConstant.FILE_UPLOAD_RESULT_BEAN: {
				// long sessionId = SerializeHelper.readLong(buffer);
				// String url = SerializeHelper.readString(buffer);
				// Mainframe.getInstance().onUploadFileResult(sessionId, url);
				// break;
				// }
				// case ClientConstant.IMAGE_RESULT_BEAN: {
				// String url = SerializeHelper.readString(buffer);
				// byte[] imageData = SerializeHelper.readBytes(buffer);
				// Mainframe.getInstance().onImageResultComing(url, imageData);
				// break;
				// }
				case ClientConstant.DOWNLOAD_FIRST_CHUNK_AUDIO_BEAN: {
					int songId = SerializeHelper.readInt(buffer);
					int nextChunk = SerializeHelper.readInt(buffer);
					int totalChunk = SerializeHelper.readInt(buffer);
					byte[] chunkData = SerializeHelper.readBytes(buffer);
					Core.getInstance().onFirstChunkAudioComing(nextChunk, chunkData, songId, totalChunk);
					break;
				}
				case ClientConstant.DOWNLOAD_NEXT_CHUNK_AUDIO_BEAN: {
					int songId = SerializeHelper.readInt(buffer);
					int nextChunk = SerializeHelper.readInt(buffer);
					byte[] chunkData = SerializeHelper.readBytes(buffer);
					Core.getInstance().onNextChunkAudioComing(nextChunk, chunkData, songId);
					break;
				}
				case ClientConstant.YAHOO_FRIEND_LIST_BEAN: {
					String yahooUsername = SerializeHelper.readString(buffer);
					int n = SerializeHelper.readInt(buffer);
//					System.out.println("YAHOO_FRIEND_LIST_BEAN n = " + n);
					DefaultListModel buddies = new DefaultListModel();
					if (n > 0) {
						for (int i = 0; i < n; i++) {
							if (SerializeHelper.readByte(buffer) != -1) {
								String ymName = SerializeHelper.readString(buffer);
								byte status = SerializeHelper.readByte(buffer);
								String statusString = SerializeHelper.readString(buffer);
								Buddy buddy = new Buddy();
								buddy.setUsername(ymName);
								buddy.setStatus(status);
								buddy.setStatusText(statusString);
								buddies.addItem(buddy);
							}
						}
						
						Core.getInstance().onYahooFriendlistComing(yahooUsername, buddies);
					}
					break;
				}
				case ClientConstant.YAHOO_NOTIFY_CHANGE_STATUS_BEAN: {
					String ymName = SerializeHelper.readString(buffer);
					byte status = SerializeHelper.readByte(buffer);
					String statusString = SerializeHelper.readString(buffer);
					Core.getInstance().onYahooNofifyChangeStatusComing(ymName, status, statusString);
					break;
				}
				case ClientConstant.YAHOO_CHAT_FROM_BEAN: {
					String username = SerializeHelper.readString(buffer);
					String msgChat = SerializeHelper.readString(buffer);
					Core.getInstance().onYahooChatFromComing(username, msgChat);
					break;
				}
				case ClientConstant.YAHOO_BUZZ_FROM_BEAN: {
					String username = SerializeHelper.readString(buffer);
					Core.getInstance().onYahooBuzztFromComing(username);
					break;
				}
				default:
					break;
				}
				msg.dispose();
			} catch (Exception e) {
			} finally {
				if (msg != null) {
					msg.dispose();
				}
				if (buffer != null) {
					buffer.close();
				}
			}
		} catch (Exception e) {
		}
	}
}